package com.xishu.util;

import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;

public class RandomUtil {
    private static final String ALL = "1234567890qwertyuiopasdfghjklzxcvbnm";

    private static final String LOWER_CHARACTER = "qwertyuiopasdfghjklzxcvbnm";


    /**
     * 产生一个随要的数字
     *
     * @param length
     * @return
     */
    public static String generateNumberCode(int length) {
        SecureRandom secureRandom = new SecureRandom();

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < length; i++) {
            //第一位不能是0
            if (i == 0) {
                int randomNumber = randomNumber(Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9));
                result.append(randomNumber);
                continue;
            }

            int number = secureRandom.nextInt(10);
            result.append(number);
        }

        return result.toString();
    }

    /**
     * 从一个集合里面选一个数
     *
     * @param integerList
     * @return
     */
    public static int randomNumber(List<Integer> integerList) {
        SecureRandom secureRandom = new SecureRandom();
        int nextInt = secureRandom.nextInt(integerList.size());

        //不能超过最大值
        if (nextInt == integerList.size()) {
            nextInt = integerList.size() - 1;
        }

        return integerList.get(nextInt);
    }

    /**
     * 产生一个随机字符串
     *
     * @param length
     * @return
     */
    public static String generateString(int length) {
        SecureRandom secureRandom = new SecureRandom();

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int position = secureRandom.nextInt(ALL.length());
            char c = ALL.charAt(position);
            result.append(c);
        }

        return result.toString();
    }

    /**
     * 产生小写字母串
     *
     * @return
     */
    public static String generateLowerCaseString(int length) {
        SecureRandom secureRandom = new SecureRandom();

        StringBuilder result = new StringBuilder();

        for (int i = 0; i < length; i++) {
            int position = secureRandom.nextInt(LOWER_CHARACTER.length());
            char c = LOWER_CHARACTER.charAt(position);
            result.append(c);
        }

        return result.toString();
    }

}
